package com.backend.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.backend.common.BaseResponse;
import com.backend.common.ErrorCode;
import com.backend.common.ResultUtils;
import com.backend.exception.BusinessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


/**
 * 上传文件映射表
 */
@RestController
@RequestMapping("file")
public class FileController{
    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    public BaseResponse<?> upload(@RequestParam("file") MultipartFile file,String type) throws Exception {
        System.out.println("文件上传开始");
        //判断文件是否为空
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件不能为空");
        }

        //获取文件后缀
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        System.out.println("文件后缀名：" + fileExt);

        // 获取当前路径
        File path = new File(ResourceUtils.getURL("file:upload/").getPath());
        System.out.println("当前静态资源路径：" + path.getAbsolutePath());

        // 当前路径是否存在
        if (!path.exists()) {
            path.mkdirs();
        }

        String fileName = new Date().getTime() + "." + fileExt;
        System.out.println("转换后的文件名：" + fileName);


        File dest = new File(path.getAbsolutePath() + "/" + fileName);
        System.out.println("将会存储的目录：" + path.getAbsolutePath() + "/" + fileName);

        //将文件上传
        file.transferTo(dest);
        System.out.println("文件上传成功！");

        return ResultUtils.ok(fileName);

    }

    /**
     * 下载文件
     */
    @RequestMapping("/download")
//    public BaseResponse<byte[]> download(@RequestParam String fileName)
    public BaseResponse<?> download(@RequestParam String fileName) {
        try {
            //获取当前类路径
            File path = new File(ResourceUtils.getURL("classpath:static").getPath());
            //如果类路径不存在，则获取当前路径
            if(!path.exists()) {
                path = new File("");
            }
            //获取上传文件夹路径
            File upload = new File(path.getAbsolutePath(),"/upload/");
            //如果上传文件夹不存在，则创建
            if(!upload.exists()) {
                upload.mkdirs();
            }
            //获取文件路径
            File file = new File(upload.getAbsolutePath()+"/"+fileName);
            //如果文件存在
            if(file.exists()){
				/*if(!fileService.canRead(file, SessionManager.getSessionUser())){
					//不能读取文件，返回403
					getResponse().sendError(403);
				}*/
                //设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", fileName);
                //返回文件内容
//                return ResultUtils.ok(FileUtils.readFileToByteArray(file));
                return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
//                return new BaseResponse<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //文件不存在，返回500
        return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
    }

}
